package com.sen.ssp.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sen.ssp.exception.SystemExceptionCode.SysCommonCode;
import com.sen.ssp.utils.ConfigManagerUtil;

/**
 * @author sen
 */
public class SspRuntimeException extends RuntimeException {

	private static final long serialVersionUID = 7490642728319542370L;

	/** slf4j logger 日志记录器  */
	private static final Logger LOG = LoggerFactory.getLogger("ssp.exception");

	// code
	private String code;
	// 消息
	private String message;
	// 异常原因
	private Throwable cause;
	
	/**
	 * 获取异常code
	 * @return 异常code
	 */
	public String getCode() {
		return code;
	}

	public SspRuntimeException(String code) {
		this(code, getShow(code), null);
	}

	public SspRuntimeException(String code, Throwable cause) {
		this(code, getShow(code), cause);
	}

	public SspRuntimeException(String code, String message, Throwable cause) {
		super(String.format("错误编码是：%s，错误提示是：%s", code, message), cause);
		this.code = code;
		this.message = message;
		this.cause = cause;
		LOG.error(getLogMessage(), cause);
	}

	public String getLogMessage() {
		if (this.cause == null) {
			return String.format("错误编码是：%s，错误提示是：%s，异常类型是：%s", code, message, this.getClass().getName());
		} else {
			return String.format("错误编码是：%s，错误提示是：%s，异常类型是：%s，异常源消息：%s", code, message, cause.getClass().getName(),
					cause.getMessage());
		}
	}

	protected static String getShow(String code) {
		try {
			return ConfigManagerUtil.getErrorInfo(code);
		} catch (Exception e) {
			return SysCommonCode.EXCEPTION_MSG_READER_ERROR + ":[" + "异常消息读取失败" + "]";
		}
	}
}
